package com.dayatang.product.webapp.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.dayatang.product.domain.Permission;
import com.dayatang.product.domain.PersonUser;
import com.dayatang.product.domain.Role;
import com.dayatang.product.domain.RoleAssignment;
import com.dayatang.product.domain.RolePermission;
import com.dayatang.product.util.EncryptUtil;
import com.dayatang.product.webapp.annotation.PMLog;

@ParentPackage(value = "web")
public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 9026129684788526304L;

	private String username;
	private String password;
	private String code;
	
	private String result;
	
	@PMLog(moduleName = "用户登录", option = "登录")
	@Action(results = {@Result(name = "success", type = "json")})
	public String execute() throws Exception {
		if (username != null && password != null && code.equals(getSessinoValue(LOGIN))) {
			PersonUser personUser = PersonUser.getByUsername(username);
			if (personUser == null) {
				result = USERNAMENOEXISTS;
			} else if (!personUser.getDisabled()) {
				result = USERDISABLE;
			} else if (RoleAssignment.findByUser(personUser).size() == 0) {
				result = NOROLE;
			} else if (RolePermission.findByRole(RoleAssignment.findByUser(personUser).get(0).getRole()).size() == 0 ) {
				result = NOPERMISSION;
			} else if (personUser.getPassword().equals(EncryptUtil.encryptString(password))) {
				setSessiolnValue(LOGINUSER, personUser);
				InitPermission(personUser);
				result = OK;
			} else {
				result = PASSWORDERROR;
			}
		} else {
			result = FAILURE;
		}
		return SUCCESS;
	}
	
	private void InitPermission(PersonUser personUser) {
		List<Permission> permissions = new ArrayList<Permission>(); 
		Role role = RoleAssignment.findByUser(personUser).get(0).getRole();
		for (RolePermission rolePermission : RolePermission.findByRole(role)) {
			permissions.add(rolePermission.getPermission());
		}
		setSessiolnValue(PERMISSIONS, permissions);
		setSessiolnValue(RESOURCES, securityApplication.getUserPermissionResource(personUser,role));
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

}
